#include "hplcpumppulsecompencalibrationpage.h"
#include "modulemanager.h"
#include "modulehplcpump.h"
#include "modulehplcpumpparamiddefine.h"
#include "modulehplccmdid.h"
#include "tableviewex.h"
#include <QDebug>
#include "mainwindow.h"
#include "flowmetersli1000.h"
#include <QSerialPort>
#include <QSerialPortInfo>

HplcPumpPulseCompenCalibrationPage::HplcPumpPulseCompenCalibrationPage(QWidget *parent) : QWidget(parent)
{
    setWindowTitle(tr("Hplc Pump Pulse Compen Calibrate Page"));
    setAttribute(Qt::WA_DeleteOnClose);

    m_timer = new QTimer();
    m_timer->setInterval(2000);
    connect(m_timer, &QTimer::timeout, this, [=](){
        if (m_widCurve)
            m_widCurve->updatePeriod();
    });

    m_tableView = new TableViewEx(this);
    m_tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    m_tableView->setSortingEnabled(true);
    QStringList headers;
    headers << tr("position") << tr("factor");
    m_tableView->setHeaders(headers);

    ModuleHplcPump *mod = static_cast<ModuleHplcPump*>(moduleManager->find(ModuleID_HPLC_PumpA));
    if (mod == nullptr)
        return;
    connect(mod, &ModuleHplcPump::parseCompleted,
            this, &HplcPumpPulseCompenCalibrationPage::onParseCompleted, Qt::QueuedConnection);

    QVariant var;
    QList<hplc::PumpPulseCompenCalibData> list;
    mod->getParam(ModuleHplcPumpParamID_PulseCompenCalibData, var);
    list.clear();
    list = var.value<QList<hplc::PumpPulseCompenCalibData>>();
    onSetData(list);

    // 进入校正模式
    m_pbWorkMode = new QPushButton();
    m_pbWorkMode->setText(tr("Enter"));
    connect(m_pbWorkMode, &QPushButton::clicked, this, [=](){
        QVariant var;
        if (QString::compare(m_pbWorkMode->text(), tr("Enter")) == 0)
        {
            var.setValue(true);
            mod->setProtocolCmd(hplc::PumpSystemCmdID_SetWorkModePulseCompenCalib, var);

            m_pbWorkMode->setText(tr("Exit"));
        }
        else
        {
            var.setValue(false);
            mod->setProtocolCmd(hplc::PumpSystemCmdID_SetWorkModePulseCompenCalib, var);

            m_pbWorkMode->setText(tr("Enter"));
        }
    });

    // 保存到板
    m_pbSet = new QPushButton();
    m_pbSet->setText(tr("Set"));
    connect(m_pbSet, &QPushButton::clicked, this, [=](){
        QList<hplc::PumpPulseCompenCalibData> list = getData();
        // 保存到模块
        QVariant var;
        var.setValue(list);
        mod->setParam(ModuleHplcPumpParamID_PulseCompenCalibData, var);

        mod->setProtocolCmd(hplc::PumpSystemCmdID_SetPulseCompenCalibData, var);
    });
    m_pbGet = new QPushButton();
    m_pbGet->setText(tr("Get"));
    connect(m_pbGet, &QPushButton::clicked, this, [=](){
        QVariant var;
        mod->getProtocolCmd(hplc::PumpSystemCmdID_GetPulseCompenCalibData, var);
    });

    m_pbSave = new QPushButton();
    m_pbSave->setText(tr("Save"));
    connect(m_pbSave, &QPushButton::clicked, this, [=](){
        QVariant var;
        var.setValue(2);
        mod->setProtocolCmd(hplc::PumpSystemCmdID_SetPulseCompenCalibDataCmd, var);
    });
    m_pbClear = new QPushButton();
    m_pbClear->setText(tr("Clear"));
    connect(m_pbClear, &QPushButton::clicked, this, [=](){
        QVariant var;
        var.setValue(3);
        mod->setProtocolCmd(hplc::PumpSystemCmdID_SetPulseCompenCalibDataCmd, var);
    });

    // 读板数据
    QVBoxLayout *vblSetGet = new QVBoxLayout();
    vblSetGet->addWidget(m_pbWorkMode);
    vblSetGet->addWidget(m_pbSet);
    vblSetGet->addWidget(m_pbGet);
    vblSetGet->addWidget(m_pbSave);
    vblSetGet->addWidget(m_pbClear);

    /*******************************************************
     ********************* 流量计 *************************
     *******************************************************/
    m_cbPort = new QComboBox();
    m_pbOpen = new QPushButton(tr("Open"));
    connect(m_pbOpen, &QPushButton::clicked, this, &HplcPumpPulseCompenCalibrationPage::onOpen);
    m_pbFind = new QPushButton(tr("Find"));
    connect(m_pbFind, &QPushButton::clicked, this, &HplcPumpPulseCompenCalibrationPage::onFind);
    m_pbStart = new QPushButton(tr("Start"));
    connect(m_pbStart, &QPushButton::clicked, this, &HplcPumpPulseCompenCalibrationPage::onStart);
    m_pbStart->setEnabled(false);
    m_hblPort = new QHBoxLayout();
    m_hblPort->addWidget(m_cbPort);
    m_hblPort->addWidget(m_pbOpen);
    m_hblStart = new QHBoxLayout();
    m_hblStart->addWidget(m_pbFind);
    m_hblStart->addWidget(m_pbStart);
    m_vblFlowmeter = new QVBoxLayout();
    m_vblFlowmeter->addLayout(m_hblPort);
    m_vblFlowmeter->addLayout(m_hblStart);

    m_gbFlowmeter = new QGroupBox();
    m_gbFlowmeter->setTitle(tr("Flowmeter SLI-1000"));
    m_gbFlowmeter->setLayout(m_vblFlowmeter);

    QHBoxLayout *hbl = new QHBoxLayout();
    hbl->addWidget(m_tableView, 5);
    hbl->addLayout(vblSetGet, 1);
    hbl->addWidget(m_gbFlowmeter, 1);
    setLayout(hbl);

    onFind();
}

HplcPumpPulseCompenCalibrationPage::~HplcPumpPulseCompenCalibrationPage()
{

}

QList<hplc::PumpPulseCompenCalibData> HplcPumpPulseCompenCalibrationPage::getData()
{
    QStandardItemModel &model = m_tableView->getModel();
    QList<hplc::PumpPulseCompenCalibData> list;
    hplc::PumpPulseCompenCalibData data;
    for (int i = 0; i < model.rowCount(); i++)
    {
        for (int j = 0; j < model.columnCount(); j++)
        {
            QVariant var = model.data(model.index(i, j), Qt::DisplayRole);

            if (j == 0)
                data.position = var.toInt();
            else if (j == 1)
                data.factor = var.toDouble();;
        }
        list << data;
    }
    foreach(auto var, list)
    {
        qDebug() << var.position << var.factor;
    }
    return list;
}

void HplcPumpPulseCompenCalibrationPage::onSetData(const QList<hplc::PumpPulseCompenCalibData> &list)
{
    QStandardItemModel &model = m_tableView->getModel();
    model.removeRows(0, model.rowCount());
    QList<QStandardItem*> items;
    QStandardItem *itemRpm, *itemRate;
    foreach (auto var, list)
    {
        itemRpm = new QStandardItem();
        itemRpm->setData(var.position, Qt::DisplayRole);
        itemRate = new QStandardItem();
        itemRate->setData(var.factor, Qt::DisplayRole);
        items.clear();
        items << itemRpm << itemRate;
        model.appendRow(items);
    }
}

void HplcPumpPulseCompenCalibrationPage::onOpen()
{
    FlowmeterSLI1000 *mod = static_cast<FlowmeterSLI1000*>(moduleManager->find(ModuleID_FlowMeterSLI1000));
    if (mod == nullptr)
        return;
    QVariant var;

    if (QString::compare(m_pbOpen->text(), tr("Open")) == 0)
    {
        var.setValue(m_cbPort->currentText());
        if (mod->setConfig(FlowmeterSLI1000::ConfigID_Open, var))
        {
            m_pbOpen->setText(tr("Close"));
        }
    }
    else
    {
        if (mod->setConfig(FlowmeterSLI1000::ConfigID_Close, var))
        {
            m_pbOpen->setText(tr("Open"));
        }
    }
}

void HplcPumpPulseCompenCalibrationPage::onFind()
{
    m_cbPort->clear();

    const auto infos = QSerialPortInfo::availablePorts();
    for (const QSerialPortInfo& info : infos)
    {
        QSerialPort serial;
        //serial->setPort(info);
        //if (serial.open(QIODevice::ReadWrite))
        {
            m_cbPort->addItem(info.portName());
            //serial.close();
        }
    }
}

void HplcPumpPulseCompenCalibrationPage::onStart()
{
    FlowmeterSLI1000 *mod = static_cast<FlowmeterSLI1000*>(moduleManager->find(ModuleID_FlowMeterSLI1000));
    if (mod == nullptr)
       return;

    m_pbStart->setEnabled(false);
    m_widCurve = new HplcPumpPulseCompenCurvePage();
    connect(m_widCurve, &QWidget::destroyed, [=](){
        m_pbStart->setEnabled(true);
        m_widCurve->disconnect();
        m_widCurve = nullptr;
        m_timer->stop();

        QVariant var;
        if (mod->setConfig(FlowmeterSLI1000::ConfigID_Stop, var))
        {
            {
                ModuleHplcPump *mod = static_cast<ModuleHplcPump*>(moduleManager->find(ModuleID_HPLC_PumpA));
                if (mod == nullptr)
                    return;
                QVariant var;
                var.setValue(0);
                mod->setProtocolCmd(hplc::PumpSystemCmdID_SetPulseCompenDebugCmd, var);
            }
        }
    });
    QMdiSubWindow *subWin = MainWindow::getInstance()->addSubWindow(m_widCurve);
    subWin->resize(MainWindow::getInstance()->size() * 2 / 3);
    m_widCurve->show();
    m_timer->start(); // test

    QVariant var;
    if (mod->setConfig(FlowmeterSLI1000::ConfigID_Start, var))
    {
        connect(mod, &FlowmeterSLI1000::getData, m_widCurve, &HplcPumpPulseCompenCurvePage::update);

        {
            ModuleHplcPump *mod = static_cast<ModuleHplcPump*>(moduleManager->find(ModuleID_HPLC_PumpA));
            if (mod == nullptr)
                return;
            QVariant var;
            var.setValue(1);
            mod->setProtocolCmd(hplc::PumpSystemCmdID_SetPulseCompenDebugCmd, var);
        }
    }
}

void HplcPumpPulseCompenCalibrationPage::closeEvent(QCloseEvent *event)
{
    disconnect();
    event->accept();
}

void HplcPumpPulseCompenCalibrationPage::onParseCompleted(int id, const QVariant &var)
{
    switch (id)
    {
        case hplc::PumpSystemCmdID_SetPulseCompenCalibData:
        {
            QList<hplc::PumpPulseCompenCalibData> list;
            list = var.value<QList<hplc::PumpPulseCompenCalibData>>();
            onSetData(list);
        }
        break;
        case hplc::PumpSystemCmdID_SetPulseCompenGearPos:
        {
            qint32 pos = var.toInt();
            Q_UNUSED(pos)
            if (m_widCurve)
                m_widCurve->updatePeriod();
        }
        break;
        default:
        break;
    }
}
